package com.xh.common.thread.ctl;

import android.os.Process;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

    private final String sNamePrefix;
    private final AtomicInteger sThreadNumber = new AtomicInteger(1);

    public NamedThreadFactory(String factoryName) {
        this.sNamePrefix = "ChenYe_" + factoryName + "#";
    }

    @Override
    public Thread newThread(Runnable r) {
        RunnableWrapper wrapper = new RunnableWrapper(r);
        return new Thread(wrapper, sNamePrefix + this.sThreadNumber.getAndIncrement());
    }

    /**
     * 封装一下Runnable，将线程的优先级调整为BACKGROUND
     */
    private static class RunnableWrapper implements Runnable {

        private Runnable mRunnable;

        RunnableWrapper(Runnable runnable) {
            mRunnable = runnable;
        }

        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            mRunnable.run();
        }
    }
}
